# -*- coding: utf-8 -*-
# @Time    : 2024/12/18 21:27
# @Author  : xiangbo
# @Email   : xiangbo@163.com
# @File    : tools.py
# @Software: PyCharm
# 其他工具模块

import os
import hashlib
import secrets
import string
import zipfile


def generate_random_string(length):
    # 生成随机字符串的函数
    letters = string.ascii_letters
    random_string = ''.join(secrets.choice(letters) for _ in range(length))
    return random_string.lower()  # 转成小写


def md5_code(passwd):
    md5 = hashlib.md5()
    md5.update(passwd.encode("utf-8"))
    return md5.hexdigest()


def trans_str(s):
    s = s.replace('":"', "=").replace('":', '=')
    return s


def zip_dir(startdir, zip_file):
    # 压缩文件
    _zip_file = os.path.join(startdir, zip_file)
    if os.path.exists(_zip_file):
        # 先删除
        os.remove(_zip_file)
    z = zipfile.ZipFile(_zip_file, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(startdir):
        fpath = dir_path.replace(startdir, '')  # 不replace的话，就从根目录开始复制

        fpath = fpath and fpath + os.sep or ''
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), fpath + filename)

    z.close()
